package com.joysuch.wwyt.app.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.zlg.common.util.CollectionUtils;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.app.bean.AppMenuBean;
import com.joysuch.wwyt.app.bean.AppPendingTaskDto;
import com.joysuch.wwyt.app.enums.AppV2TaskTypes;
import com.joysuch.wwyt.app.service.AppCommonService;
import com.joysuch.wwyt.bp.bean.AppPendingTaskBean;
import com.joysuch.wwyt.bp.bean.inspect.BpInspectManageDto;
import com.joysuch.wwyt.bp.bean.investigate.BpInvestigateAppTaskDto;
import com.joysuch.wwyt.bp.bean.safetyworkcert.BpWorkSafetyAppListBean;
import com.joysuch.wwyt.bp.entity.BpWorkSafetyCert;
import com.joysuch.wwyt.bp.entity.inspect.BpAppPlanTask;
import com.joysuch.wwyt.bp.entity.inspect.BpInspectPlan;
import com.joysuch.wwyt.bp.enums.PendingTaskType;
import com.joysuch.wwyt.bp.repository.BpWorkSafetyCertDao;
import com.joysuch.wwyt.bp.service.BpInspectPlanService;
import com.joysuch.wwyt.bp.service.BpInvestigatePlanService;
import com.joysuch.wwyt.bp.service.BpWorkSafetyCertService;
import com.joysuch.wwyt.core.bean.SimpleSelectListBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.DateTimeUtil;
import com.joysuch.wwyt.core.common.util.SimpleDateFormatCache;
import com.joysuch.wwyt.core.constant.Constants;
import com.joysuch.wwyt.core.entity.BaseMenuFunction;
import com.joysuch.wwyt.core.enums.MenuTypes;
import com.joysuch.wwyt.core.repository.BaseMenuFunctionDao;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.AuthorityService;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.edu.bean.EduExamCenterListBean;
import com.joysuch.wwyt.edu.service.EduExamService;
import com.joysuch.wwyt.workflow.api.service.NewProcessService;
import com.joysuch.wwyt.workflow.bean.WorkFlowProcessTaskQueryBean;
import com.joysuch.wwyt.workflow.bean.WorkFlowTaskQueryBean;
import com.joysuch.wwyt.workflow.entity.WorkFlowProcess;
import com.joysuch.wwyt.workflow.entity.WorkFlowTask;
import com.joysuch.wwyt.workflow.entity.dto.WorkflowTaskDto;
import com.joysuch.wwyt.workflow.enums.WorkFlowProcessEnum;
import com.joysuch.wwyt.workflow.repository.WorkFlowProcessDao;
import com.joysuch.wwyt.workflow.service.WorkFlowHiddenDangerService;
import com.joysuch.wwyt.workflow.service.WorkFlowTaskProcessListService;
import com.joysuch.wwyt.workflow.service.WorkFlowTaskService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class AppCommonServiceImpl implements AppCommonService {

    @Autowired
    private WorkFlowHiddenDangerService workFlowHiddenDangerService;
    @Autowired
    private BpWorkSafetyCertDao bpWorkSafetyCertDao;
    @Autowired
    private BaseMenuFunctionDao menuFunctionDao;
    @Autowired
    private BpInspectPlanService bpInspectPlanService;
    @Autowired
    private AuthorityService authorityService;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private EduExamService eduExamService;
    @Autowired
    private BpWorkSafetyCertService bpWorkSafetyCertService;
    @Autowired
    private WorkFlowProcessDao workFlowProcessDao;
    @Autowired
    private WorkFlowTaskService workFlowTaskService;
    @Autowired
    private BpInvestigatePlanService investigatePlanService;
    @Autowired
    private WorkFlowTaskProcessListService workFlowTaskProcessListService;
    @Autowired
    private NewProcessService newProcessService;

    @Override
    public ResultBean v2AppMenuList() {
        return ResultBean.wrapSuccessfulResult(currentUserMenu());
    }

    @Override
    public ResultBean v2WorkSafetyMenu(Long id) {
        Assert.notNull(id, "id cannot be null");
        BaseMenuFunction menuFunction = menuFunctionDao.findById(id).orElseThrow(() -> new IllegalArgumentException("此菜单不存在"));

        //查询当前用户授权的菜单
        Long userId = Context.getCurrentUserId();
        boolean isSuperAdmin = Context.getCurrentUser().isSuperAdmin();
        List<BaseMenuFunction> menuList = authorityService.queryMenuFunctionByUserId(userId, isSuperAdmin);
        List<Long> menuIdList = menuList.stream().map(r -> r.getId()).collect(Collectors.toList());

        List<BaseMenuFunction> childList = menuFunctionDao.findByParent(menuFunction);
        if (CollectionUtils.isEmpty(childList)) {
            return ResultBean.defaultSuccessResult();
        }
        childList = childList.stream().filter(r -> r.getShowState() != null && r.getShowState() == 1
                && "是".equals(r.getAppFlag())).collect(Collectors.toList());
        Iterator<BaseMenuFunction> iterator = childList.iterator();
        while (iterator.hasNext()) {
            BaseMenuFunction function = iterator.next();
            //如果app菜单名为空则默认用web菜单名
            if (StringUtils.isBlank(function.getAppName())) {
                function.setAppName(function.getName());
            }
            if (!menuIdList.contains(function.getId())) {
                iterator.remove();
            } else {
                function.setParent(null);
                List<BaseMenuFunction> tempList = menuFunctionDao.findByParent(function);
                tempList = tempList.stream().filter(r -> r.getShowState() != null && r.getShowState() == 1 && "是".equals(r.getAppFlag()))
                        .sorted(Comparator.comparing(BaseMenuFunction::getMenuOrder)).collect(Collectors.toList());
                Iterator<BaseMenuFunction> tempIterator = tempList.iterator();
                while (tempIterator.hasNext()) {
                    BaseMenuFunction next = tempIterator.next();
                    if (!menuIdList.contains(next.getId())) {
                        tempIterator.remove();
                    } else {
                        next.setParent(null);
                    }
                }
                function.setChildList(tempList);
            }
        }
        childList.sort(Comparator.comparing(BaseMenuFunction::getMenuOrder));
        return ResultBean.success(childList);
    }

    @Override
    public List<AppMenuBean> v3AppMenuList() {
        Long userId = Context.getCurrentUserId();
        boolean isSuperAdmin = Context.getCurrentUser().isSuperAdmin();
        List<BaseMenuFunction> menuList = authorityService.findAppMenuList(userId, isSuperAdmin);
        List<BaseMenuFunction> folderMenuList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(menuList)){
            List<BaseMenuFunction> folderMenu = menuList.stream().filter(each -> MenuTypes.FOLDER.getCode().equals(each.getType())).collect(Collectors.toList());
            folderMenuList.addAll(folderMenu);
        }
            List<Long> childMenuIds = new ArrayList<>();
            //过滤菜单集合下面的二级菜单，二级菜单会独立显示，目前只考虑二级
            if (CollectionUtils.isNotEmpty(folderMenuList)) {
                folderMenuList.forEach(each -> {
                    ResultBean bean = v2WorkSafetyMenu(each.getId());
                    List<BaseMenuFunction> taskList = (List<BaseMenuFunction>) bean.getData();
                    if (CollectionUtils.isNotEmpty(taskList)) {
                        taskList.forEach(menu -> childMenuIds.add(menu.getId()));
                    }
                });
            }

            List<AppMenuBean> tempList = Lists.newArrayList();
            if (CollectionUtils.isNotEmpty(menuList)) {
                for (BaseMenuFunction baseMenu : menuList) {
                    if (!childMenuIds.contains(baseMenu.getId())) {
                        AppMenuBean appMenu = new AppMenuBean();
                        String webMenuName = baseMenu.getName();
                        String appMenuName = baseMenu.getAppName();
                        appMenu.setMenuName(StringUtils.isNotBlank(appMenuName) ? appMenuName : webMenuName);
                        appMenu.setWorkFlowId(baseMenu.getWorkFlowId());
                        appMenu.setIcon(baseMenu.getIcon());
                        appMenu.setId(baseMenu.getId());
                        appMenu.setMenuType(baseMenu.getType());
                        appMenu.setAppMenuUrl(baseMenu.getAppMenuUrl());
                        appMenu.setModelId(baseMenu.getModelId());
                        tempList.add(appMenu);
                    }
                }
            }
            return tempList;
        }




    private AppMenuBean formatAppMenu(BaseMenuFunction menu, String appMenuName) {
        AppMenuBean bean = new AppMenuBean();
        bean.setMenuName(appMenuName);
        bean.setWorkFlowId(menu.getWorkFlowId());
        bean.setIcon(menu.getIcon());
        bean.setId(menu.getId());
        return bean;
    }

    /**
     * app/v2 待办事项包含: 巡检任务、作业审核、作业验收、隐患整改、整改验收、考试通知、工作流程
     */
    @Override
    public ResultBean v2PendingTaskList(Integer type) {
        List<AppPendingTaskDto> resultList = Lists.newArrayList();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd HH:mm");
        List<AppMenuBean> appMenuBeans = currentUserMenu();
        if (type == null || type == 0) {
            //巡检任务
            List<AppPendingTaskDto> inspectPlanList = getInspectPlanList(appMenuBeans, formatter);
            //3.隐患管理: 整改管理+整改验收
//        List<AppPendingTaskDto> hiddenManagerList = getHiddenManagerList(appMenuBeans, formatter);
            //教育
            List<AppPendingTaskDto> eduList = getEduPending(appMenuBeans, formatter);

            //作业审核
            List<AppPendingTaskDto> safetyAuditList = getSafetyAudit(appMenuBeans, formatter);
            //作业验收
            List<AppPendingTaskDto> safetyCheckList = getSafetyCheck(appMenuBeans, formatter);

            //作业票
            //List<AppPendingTaskDto> safetyList = getWorkSafety();

            //隐患排查
            List<AppPendingTaskDto> investigateTaskList = getInvestigateTask(appMenuBeans);

            //resultList.addAll(safetyList);
            resultList.addAll(inspectPlanList);
            //resultList.addAll(hiddenManagerList);
            resultList.addAll(eduList);
            resultList.addAll(safetyAuditList);
            resultList.addAll(safetyCheckList);
            resultList.addAll(investigateTaskList);
        }

        if (type == null || type == 1) {
            //待办默认取200条
            List<AppPendingTaskDto> todoTaskList = getToDoTaskList();
            resultList.addAll(todoTaskList);

            List<AppPendingTaskDto> taskDtoList = newProcessService.todoList();
            resultList.addAll(taskDtoList);
            // 查找新流程引擎 待办事项
        }

        resultList.sort(Comparator.comparing(AppPendingTaskDto::getLocalDateTime).reversed());
        return ResultBean.wrapSuccessfulResult(resultList);
    }

    private List<AppPendingTaskDto> getInvestigateTask(List<AppMenuBean> appMenuBeans) {
        List<AppPendingTaskDto> investigateTaskList = Lists.newArrayList();
        if (hasMenuAuth("隐患排查", appMenuBeans)) {
            List<BpInvestigateAppTaskDto> taskDtoList = investigatePlanService.appNeedDo();
            for (BpInvestigateAppTaskDto taskDto : taskDtoList) {
                AppPendingTaskDto dto = new AppPendingTaskDto();
                dto.setTaskName(AppV2TaskTypes.INVESTIGATE_TASK.getTypeName());
                dto.setShowFirst(taskDto.getPlanName());
                dto.setShowSecond(taskDto.getTypeName());
                dto.setShowThird(LocalDate.now().toString());
                dto.setId(taskDto.getPlanId());
                dto.setLocalDateTime(LocalDateTimeUtil.now());
                dto.setTaskId(taskDto.getTaskId());
                investigateTaskList.add(dto);
            }
        }
        return investigateTaskList;
    }

    private List<AppPendingTaskDto> getToDoTaskList() {
        List<AppPendingTaskDto> toDoTaskList = Lists.newArrayList();
        WorkFlowProcessTaskQueryBean queryBean = new WorkFlowProcessTaskQueryBean();
        queryBean.setPage(1);
        queryBean.setSize(200);
        queryBean.setWorkFlowProcess(WorkFlowProcessEnum.TO_DO_TASK.getValue());
        ResultBean resultBean = workFlowTaskProcessListService.findProcessList(queryBean);
        List<WorkflowTaskDto> taskList = (List<WorkflowTaskDto>) resultBean.getData();
        List<Long> processIds = taskList.stream().map(WorkflowTaskDto::getProcessId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(processIds)) {
            List<WorkFlowProcess> processList = workFlowProcessDao.findAllById(processIds);
            Map<Long, WorkFlowProcess> processMap = processList.stream().collect(Collectors.toMap(WorkFlowProcess::getId, Function.identity()));
            taskList.forEach(each -> {
                AppPendingTaskDto dto = new AppPendingTaskDto();
                dto.setTaskName(each.getTaskName());
                dto.setShowFirst(each.getTaskCode());
                dto.setShowSecond(DateUtil.format(each.getUpdateTime(), DatePattern.NORM_DATETIME_PATTERN));
                dto.setShowThird(each.getCurState());
                dto.setWorkFlowId(each.getProcessId());
                dto.setOperationTypes(each.getOperationTypes());
                dto.setFormData(each.getFormData());
                dto.setObjectId(each.getObjectId());
                dto.setTaskId(each.getTaskId());
                dto.setBizName(each.getBizName());
                dto.setCreateByName(each.getCreateByName());
                dto.setLocalDateTime(LocalDateTimeUtil.of(each.getUpdateTime()));
                dto.setId(each.getId());
                WorkFlowProcess workFlowProcess = processMap.get(each.getProcessId());
                if (workFlowProcess != null) {
                    String dhAddressKey = workFlowTaskProcessListService.findProcessFormJsonKey("作业地点", workFlowProcess.getFormJson());
                    String dhAddress = workFlowTaskProcessListService.findTaskFromDataValByKey(dhAddressKey, each.getFormData());
                    dto.setDhAddress(dhAddress);
                    String dhContentKey = workFlowTaskProcessListService.findProcessFormJsonKey("作业内容", workFlowProcess.getFormJson());
                    String dhContent = workFlowTaskProcessListService.findTaskFromDataValByKey(dhContentKey, each.getFormData());
                    dto.setDhContent(dhContent);
                }
                toDoTaskList.add(dto);
            });
        }
        return toDoTaskList;
    }

    private List<AppPendingTaskDto> getInspectPlanList(List<AppMenuBean> appMenuBeans, DateTimeFormatter formatter) {
        List<AppPendingTaskDto> inspectPlanList = Lists.newArrayList();
        if (hasMenuAuth("巡检管理", appMenuBeans)) {
            ResultBean resultBean = bpInspectPlanService.appNeedDo(null);
            List<BpInspectPlan> planList = (List<BpInspectPlan>) resultBean.getData();
            if (!CollectionUtils.isEmpty(planList)) {
                for (BpInspectPlan plan : planList) {
                    LocalTime localTime = plan.getCheckTimeList().get(0).getCheckTime();
                    LocalDateTime localDateTime = LocalDateTime.of(LocalDate.now(), localTime);
                    AppPendingTaskDto dto = new AppPendingTaskDto();
                    dto.setTaskName(AppV2TaskTypes.INSPECT.getTypeName());
                    //巡检名称
                    dto.setShowFirst(plan.getName());
                    //开始时间
                    dto.setShowSecond(localDateTime.format(formatter));
                    //巡检周期
                    dto.setShowThird(plan.getAppInspectPeriod());
                    dto.setId(plan.getId());
                    dto.setLocalDateTime(localDateTime);
                    inspectPlanList.add(dto);
                }
            }
        }
        return inspectPlanList;
    }

    private List<AppPendingTaskDto> getHiddenManagerList(List<AppMenuBean> appMenuBeans, DateTimeFormatter formatter) {
        List<AppPendingTaskDto> hiddenManagerList = Lists.newArrayList();
        if (hasMenuAuth(AppV2TaskTypes.HIDDEN_REPAIR.getTypeName(), appMenuBeans)) {
            List<String> taskNameList = new ArrayList<>();
            taskNameList.add(PendingTaskType.HD_RECTIFY.getName());
            taskNameList.add(PendingTaskType.HD_ACCEPT.getName());
            List<WorkFlowTask> hiddenList = workFlowHiddenDangerService.getPendTaskList(taskNameList);
            if (!CollectionUtils.isEmpty(hiddenList)) {
                for (WorkFlowTask workFlowTask : hiddenList) {
                    AppPendingTaskDto dto = new AppPendingTaskDto();
                    LocalDateTime localDateTime = DateTimeUtil.date2LocalDateTime(workFlowTask.getUpdateTime());
                    dto.setTaskName(workFlowTask.getTaskName());
                    dto.setId(workFlowTask.getId());
                    //整改期限
                    dto.setShowFirst(localDateTime.format(formatter));
                    //整改人
                    dto.setShowSecond(baseUserDao.getBaseUserNameById(Long.valueOf(workFlowTask.getAssignValue())));
                    dto.setLocalDateTime(localDateTime);
                    dto.setWorkFlowId(workFlowTask.getProcessId());
                    hiddenManagerList.add(dto);
                }
            }
        }
        return hiddenManagerList;
    }

    private List<AppPendingTaskDto> getWorkSafety() {
        List<AppPendingTaskDto> resultList = Lists.newArrayList();
        List<WorkFlowProcess> list = workFlowProcessDao.findByBizTypeName("作业票");
        if (CollectionUtils.isEmpty(list)) {
            return resultList;
        }
        Map<Long, String> bizNameMap = list.stream().collect(Collectors.toMap(WorkFlowProcess::getId, WorkFlowProcess::getBizName));
        List<WorkFlowTask> taskList = Lists.newArrayList();
        for (WorkFlowProcess workFlowProcess : list) {
            WorkFlowTaskQueryBean queryBean = new WorkFlowTaskQueryBean();
            queryBean.setWorkFlowProcessId(workFlowProcess.getId());
            queryBean.setTaskName(Lists.newArrayList());
            taskList.addAll((List<WorkFlowTask>) workFlowTaskService.findTaskList(queryBean, null).getData());
        }
        if (CollectionUtils.isEmpty(taskList)) {
            return resultList;
        }
        for (WorkFlowTask workFlowTask : taskList) {
            if (workFlowTask.getStatus() != null && workFlowTask.getStatus() == 1) {
                continue;
            }
            AppPendingTaskDto dto = new AppPendingTaskDto();
            dto.setTaskName(bizNameMap.getOrDefault(workFlowTask.getProcessId(), "作业票"));
            String formData = workFlowTask.getFormData();
            String status = "";
            if (!StringUtils.isEmpty(formData)) {
                JSONObject jsonObject = JSONObject.parseObject(formData);
                status = jsonObject.getString("状态");
            }
            dto.setShowFirst(workFlowTask.getTaskName() + "-" + (status == null ? "" : status));
            SimpleDateFormat format = SimpleDateFormatCache.getYmdhms();
            //任务产生时间
            Date updateTime = workFlowTask.getUpdateTime();
            dto.setShowSecond(format.format(updateTime));
            dto.setLocalDateTime(DateTimeUtil.date2LocalDateTime(updateTime));
            dto.setId(workFlowTask.getId());
            dto.setWorkFlowId(workFlowTask.getProcessId());
            resultList.add(dto);
        }
        return resultList;
    }

    private List<AppPendingTaskDto> getEduPending(List<AppMenuBean> appMenuBeans, DateTimeFormatter formatter) {
        List<AppPendingTaskDto> eduList = Lists.newArrayList();
        if (hasMenuAuth("教育培训", appMenuBeans)) {
            Pageable pageable = PageRequest.of(0, 100);
            EduExamCenterListBean.SearchEduExamCenter search = new EduExamCenterListBean.SearchEduExamCenter();
            search.setState("undo");
            Page<EduExamCenterListBean> page = eduExamService.queryUserExamCenterPage(pageable, Context.getCurrentUserId(), search);
            for (EduExamCenterListBean bean : page) {
                AppPendingTaskDto dto = new AppPendingTaskDto();
                dto.setTaskName(AppV2TaskTypes.EXAM_NOTIFY.getTypeName());
                LocalDateTime localDateTime = DateTimeUtil.date2LocalDateTime(bean.getStartTime());
                dto.setLocalDateTime(localDateTime);
                dto.setShowFirst(localDateTime.format(formatter));
                dto.setShowSecond(bean.getName());
                dto.setId(bean.getId());
                eduList.add(dto);
            }
        }
        return eduList;
    }

    private List<AppPendingTaskDto> getSafetyAudit(List<AppMenuBean> appMenuBeans, DateTimeFormatter formatter) {
        List<AppPendingTaskDto> safetyAuditList = Lists.newArrayList();
        if (hasMenuAuth("作业证审核", appMenuBeans)) {
            ResultBean appWaitAuditList = bpWorkSafetyCertService.getWaitForAuditList(PageRequest.of(0, 100));
            List<BpWorkSafetyAppListBean> BpWorkSafetyAppListBeans = (List<BpWorkSafetyAppListBean>) appWaitAuditList.getData();
            for (BpWorkSafetyAppListBean bean : BpWorkSafetyAppListBeans) {
                AppPendingTaskDto dto = new AppPendingTaskDto();
                dto.setTaskName(AppV2TaskTypes.CERT_AUDIT.getTypeName());
                LocalDateTime localDateTime = DateTimeUtil.date2LocalDateTime(bean.getApplyTime());
                dto.setLocalDateTime(localDateTime);
                //作业名称
                dto.setShowFirst(bean.getType());
                //作业类型编码
                dto.setShowSecond(bean.getTypeName());
                //申请人
                dto.setShowThird(bean.getApplyUserName());
                dto.setId(bean.getId());
                safetyAuditList.add(dto);
            }
        }
        return safetyAuditList;
    }

    private List<AppPendingTaskDto> getSafetyCheck(List<AppMenuBean> appMenuBeans, DateTimeFormatter formatter) {
        List<AppPendingTaskDto> safetyCheckList = Lists.newArrayList();
        if (hasMenuAuth("作业验收", appMenuBeans)) {
            ResultBean appWaitCheckList = bpWorkSafetyCertService.getWaitForCheckList(PageRequest.of(0, 100));
            List<BpWorkSafetyAppListBean> BpWorkSafetyAppListBeans = (List<BpWorkSafetyAppListBean>) appWaitCheckList.getData();
            for (BpWorkSafetyAppListBean bean : BpWorkSafetyAppListBeans) {
                AppPendingTaskDto dto = new AppPendingTaskDto();
                dto.setTaskName(AppV2TaskTypes.CERT_CHECK.getTypeName());
                LocalDateTime localDateTime = DateTimeUtil.date2LocalDateTime(bean.getApplyTime());
                dto.setLocalDateTime(localDateTime);
                //作业名称
                dto.setShowFirst(bean.getType());
                //作业类型编码
                dto.setShowSecond(bean.getTypeName());
                //申请人
                dto.setShowThird(bean.getApplyUserName());
                dto.setId(bean.getId());
                safetyCheckList.add(dto);
            }
        }
        return safetyCheckList;
    }

    private List<AppMenuBean> currentUserMenu() {
        Long userId = Context.getCurrentUserId();
        boolean isSuperAdmin = Context.getCurrentUser().isSuperAdmin();
        List<BaseMenuFunction> menuList = authorityService.queryMenuFunctionByUserId(userId, isSuperAdmin);
        //过滤菜单
        List<AppMenuBean> tempList = Lists.newArrayList();
        for (BaseMenuFunction bean : menuList) {
            if (bean.getName() == null) {
                continue;
            }
            //不是app 菜单
            if (bean.getAppFlag() == null || "否".equals(bean.getAppFlag())) {
                continue;
            }
            if (bean.getShowState() != null && bean.getShowState() == 0) {
                continue;
            }

            //流程引擎菜单特殊处理 ,单独处理后，待办事项查任务时还是得写死
//            if (bean.getWorkFlowId() != null) {
//                //隐患流程(隐患管理和隐患排查治理)不在此处理，因为它比较特殊，分了几个子模块
//                if (bean.getDepth() == 2 && "folder".equals(bean.getType())
//                        && !"隐患管理".equals(bean.getName()) && !"隐患排查治理".equals(bean.getName())) {
//                    addMenuList(tempList, formatAppMenu(bean, bean.getName()), null);
//                    continue;
//                }
//            }


            String label = bean.getName();
            switch (label) {
                case "隐患排查计划":
                    addMenuList(tempList, formatAppMenu(bean, "隐患排查"), bean.getParent() != null ? bean.getParent().getName() : null);
                    break;
                case "隐患整改":
                    addMenuList(tempList, formatAppMenu(bean, label), bean.getParent() != null ? bean.getParent().getName() : null);
                    break;
                case "整改验收":
                    addMenuList(tempList, formatAppMenu(bean, label), bean.getParent() != null ? bean.getParent().getName() : null);
                    break;
                case "检查记录":
                    addMenuList(tempList, formatAppMenu(bean, "巡检管理"), null);
                    break;
//                case "风险分级管控":
//                    addMenuList(tempList, formatAppMenu(bean, "风险管控"), null);
//                    break;
                case "作业证审核":
                    addMenuList(tempList, formatAppMenu(bean, label), null);
                    break;
                case "隐患登记":
                    addMenuList(tempList, formatAppMenu(bean, label), bean.getParent() != null ? bean.getParent().getName() : null);
                    break;
                case "风险点管理":
                    addMenuList(tempList, formatAppMenu(bean, "风险上报"), null);
                    break;
                case "课程中心":
                    addMenuList(tempList, formatAppMenu(bean, "教育培训"), null);
                    break;
                case "考试中心":
                    addMenuList(tempList, formatAppMenu(bean, "教育培训"), null);
                    break;
                case "作业证验收":
                    addMenuList(tempList, formatAppMenu(bean, "作业验收"), null);
                    break;
                case "公司级":
                    addMenuList(tempList, formatAppMenu(bean, "研判承诺"), null);
                    break;
                case "作业证申请":
                    addMenuList(tempList, formatAppMenu(bean, "作业申请"), null);
                    break;
                case "报警中心":
                    addMenuList(tempList, formatAppMenu(bean, "报警中心"), null);
                    break;
                case "统计中心":
                    addMenuList(tempList, formatAppMenu(bean, "统计中心"), null);
                    break;
                //作业票，固定字段
                case "作业票":
                    addMenuList(tempList, formatAppMenu(bean, "作业票"), null);
                    break;
                case "隐患治理":
                    addMenuList(tempList, formatAppMenu(bean, "隐患治理"), null);
                    break;
                default:
            }
        }
        return tempList;
    }

    private void addMenuList(List<AppMenuBean> tempList, AppMenuBean bean, String parentMenuName) {
        //隐患管理和隐患排查治理两个菜单下有部分菜单重名, app只取隐患管理菜单下面的
        if (parentMenuName != null && !"隐患管理".equals(parentMenuName)) {
            return;
        }
        for (AppMenuBean appMenuBean : tempList) {
            if (appMenuBean.getMenuName().equals(bean.getMenuName())) {
                return;
            }
        }
        tempList.add(bean);
    }

    /**
     * 当前用户是否有此菜单权限
     */
    private boolean hasMenuAuth(String menu, List<AppMenuBean> appMenuBeans) {
        for (AppMenuBean appMenuBean : appMenuBeans) {
            if (menu.equals(appMenuBean.getMenuName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * App 获取待办列表 ： 巡检计划， 作业， 隐患， 教育
     */
    @Override
    public List<AppPendingTaskBean> getPendingTaskList() {
        List<AppPendingTaskBean> pendingList = new ArrayList<>();

        // 1.巡检计划
        Object planObj = bpInspectPlanService.appInit().getData();
        if (planObj != null) {
            BpInspectManageDto bpInspectManageDto = (BpInspectManageDto) planObj;
            AppPendingTaskBean plan = convertInspectPlan(bpInspectManageDto);
            if (plan != null) {
                pendingList.add(plan);
            }
        }
        //2.作业管理  2.1-待申请列表
        List<BpWorkSafetyCert> workList = bpWorkSafetyCertDao.findPendingWorkApplyList(Context.getCurrentUserId());
        if (!workList.isEmpty()) {
            pendingList.addAll(convertWorkCert(workList));
        }

        Long userId = Context.getCurrentUserId();
        boolean isSuperAdmin = Context.getCurrentUser().isSuperAdmin();
        List<SimpleSelectListBean> menuList = authorityService.queryMenuListByUserId(userId, isSuperAdmin);

        // 作业管理  -2.2待审核列表: 判断是否存在审核菜单权限
        boolean hasPerm = hasPermCheck(Constants.WORK_MENU_NAME_APPROVE, isSuperAdmin, menuList);
        if (hasPerm) {
            List<BpWorkSafetyCert> applyList = bpWorkSafetyCertDao.findPendingWorkApproveList();
            if (!applyList.isEmpty()) {
                pendingList.addAll(convertWorkCert(applyList));
            }
        }

        //作业管理  -2.3待验收列表: 判断是否存在验收菜单权限
        hasPerm = hasPermCheck(Constants.WORK_MENU_NAME_ACCEPT, isSuperAdmin, menuList);
        if (hasPerm) {
            List<BpWorkSafetyCert> acceptList = bpWorkSafetyCertDao.findPendingWorkAcceptList();
            if (!acceptList.isEmpty()) {
                pendingList.addAll(convertWorkCert(acceptList));
            }
        }

        //3.隐患管理 ： 整改管理+整改验收
        hasPerm = hasPermCheck(Constants.MENU_NAME_HIDDEN_DANGER, isSuperAdmin, menuList);
        List<String> taskNameList = new ArrayList<>();
        taskNameList.add(PendingTaskType.HD_RECTIFY.getName());
        taskNameList.add(PendingTaskType.HD_ACCEPT.getName());
        List<WorkFlowTask> hiddenList = workFlowHiddenDangerService.getPendTaskList(taskNameList);
        if (!hiddenList.isEmpty()) {
            pendingList.addAll(convertHiddenDanger(hiddenList));
        }

        //4.教育培训
        hasPerm = hasPermCheck(Constants.MENU_NAME_EDU_TRAINING, isSuperAdmin, menuList);
        //TODO 添加教育待办列表


        return pendingList;
    }


    private boolean hasPermCheck(String menuName, boolean isSuperAdmin, List<SimpleSelectListBean> list) {
        if (isSuperAdmin) {
            return menuFunctionDao.findByName(menuName) != null;
        } else {
            return list.stream().filter(item -> item.getLabel().equalsIgnoreCase(menuName)).count() > 0;
        }

    }

    // 巡检计划转换
    private AppPendingTaskBean convertInspectPlan(BpInspectManageDto bpInspectManageDto) {
        AppPendingTaskBean bean = null;
        BpInspectPlan bpInspectPlan = bpInspectManageDto.getBpInspectPlan();
        BpAppPlanTask bpAppPlanTask = bpInspectManageDto.getBpAppPlanTask();
        if (bpInspectPlan != null && bpAppPlanTask != null) {
            bean = new AppPendingTaskBean();

            bean.setTaskName(PendingTaskType.INSPECT_PLAN.getName());
            bean.setTaskType(PendingTaskType.INSPECT_PLAN.getCode());
            bean.setTaskId(bpInspectPlan.getId());
            bean.setAppTaskId(bpAppPlanTask.getId());
            bean.setTaskContent(bpInspectPlan.getName());
            LocalDateTime startDateTime = bpAppPlanTask.getCheckTime().atDate(bpAppPlanTask.getCheckDate());
            bean.setStartTime(DateTimeUtil.localDateTime2Date(startDateTime));

        }
        return bean;
    }

    // 作业管理转换
    private List<AppPendingTaskBean> convertWorkCert(List<BpWorkSafetyCert> list) {
        List<AppPendingTaskBean> rtList = new ArrayList<>();
        for (BpWorkSafetyCert bean : list) {
            AppPendingTaskBean t = new AppPendingTaskBean();
            t.setTaskId(bean.getId());
            //待审批
            if (bean.getState() == 1) {
                t.setTaskName(PendingTaskType.WORK_APPROVE.getName());
                t.setTaskType(PendingTaskType.WORK_APPROVE.getCode());
                t.setStartTime(bean.getApplyTime());
                //获取内容
                t.setTaskContent(bean.getType() + "作业证");
            } else if (bean.getState() == 2) {
                //待验收
                t.setTaskName(PendingTaskType.WORK_ACCEPT.getName());
                t.setTaskType(PendingTaskType.WORK_ACCEPT.getCode());
                t.setStartTime(bean.getAuditTime());
                t.setTaskContent(bean.getType() + "作业证");
            } else if (bean.getState() == 0 || bean.getState() == 3) {
                //待申请
                t.setTaskName(PendingTaskType.WORK_APPLY.getName());
                t.setTaskType(PendingTaskType.WORK_APPLY.getCode());
                t.setStartTime(bean.getApplyTime());
                t.setTaskContent(bean.getType() + "作业证");
            }
            rtList.add(t);
        }
        return rtList;
    }


    // 隐患管理转换
    private List<AppPendingTaskBean> convertHiddenDanger(List<WorkFlowTask> list) {
        List<AppPendingTaskBean> rtList = new ArrayList<>();
        for (WorkFlowTask task : list) {
            AppPendingTaskBean t = new AppPendingTaskBean();
            t.setTaskId(task.getId());
            t.setTaskName(task.getTaskName());
            t.setTaskType(PendingTaskType.HD_RECTIFY.getName().equals(task.getTaskName()) ? PendingTaskType.HD_RECTIFY.getCode() : PendingTaskType.HD_ACCEPT.getCode());
            t.setStartTime(task.getUpdateTime());
            //获取隐患描述
            String formData = task.getFormData();
            if (formData != null) {
                JSONObject json = JSONObject.parseObject(formData);
                t.setTaskContent(json.get("隐患描述") == null ? "" : json.get("隐患描述").toString());
            }
            rtList.add(t);
        }
        return rtList;
    }

}
